#include <iostream>
#include "mysql.h"
#include "comm.hpp"

// URL 解码函数
std::string urlDecode(const std::string& str) {
    std::string ret;
    char ch;
    int i, ii;
    for (i = 0; i < str.length(); i++) {
        if (int(str[i]) == 37) 
        {
            sscanf(str.substr(i + 1, 2).c_str(), "%x", &ii);
            ch = static_cast<char>(ii);
            ret += ch;
            i = i + 2;
        } else 
        {
            ret += str[i];
        }
    }
    return (ret);
}

bool InsertSql(std::string& sql)
{
    MYSQL* conn = mysql_init(nullptr);
    if (conn == nullptr) {
        std::cout << "mysql_init failed!" << std::endl;
        return false;
    }
    
    if(mysql_real_connect(conn, "127.0.0.1", "http_test", "12345678", "http_test", 3306, nullptr, 0) == nullptr)
    {
        std::cout << "mysql_real_connect failed! Error: " << mysql_error(conn) << std::endl;
        mysql_close(conn);
        return false;
    }

    // 设置字符集为 utf8mb4
    if (mysql_set_character_set(conn, "utf8mb4")) {
        std::cout << "Failed to set character set: " << mysql_error(conn) << std::endl;
        mysql_close(conn);
        return false;
    }

    std::cerr << "connect success!" << std::endl;

    std::cerr << "query: " << sql << std::endl;
    int ret = mysql_query(conn, sql.c_str());
    std::cerr << "result: " << ret << std::endl;

    mysql_close(conn);
    return true;
}

int main()
{
    std::string query_string;
    if(GetQueryString(query_string))
    {
        std::cerr << "query_string: " << query_string << std::endl;

        // 数据处理
        std::string name, password;
        CutString(query_string, "&", name, password);

        std::string _name, sqlname;
        CutString(name, "=", _name, sqlname);

        std::string _password, sqlpassword;
        CutString(password, "=", _password, sqlpassword);

        // 进行 URL 解码
        sqlname = urlDecode(sqlname);
        sqlpassword = urlDecode(sqlpassword);
        
        std::string sql = "insert into user (name, password) values (\'";
        sql += sqlname;
        sql += "\', \'";
        sql += sqlpassword;
        sql += "\')";

        // 插入数据库
        if(InsertSql(sql))
        {
            std::cout << "<html>";
            std::cout << "<head><meta charset=\"utf-8\"></head>";
            std::cout << "<body>";
            std::cout << "<h3>注册成功</h3>";
            std::cout << "</body>";
            std::cout << "</html>";
        }
    }

    return 0;
}